<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/11
 * Time: 10:59
 */

namespace Lm\Controllers;

use \Admin\Frontend\Controllers\ControllerBase;
use Helpers\Assets;
use Helpers\Main;
use Helpers\Hrm;
use Helpers\Template;
use Helpers\XhException;
use Helpers\Tool;
use Helpers\User;
use Admin\Models\lm\XHLmGoods;
use Admin\Models\lm\XHLmGoodsIn;
use Admin\Models\lm\XHLmGoodsOut;
use Admin\Models\lm\XHLmGoodsType;
use Admin\Models\hrm\XhhrmStaff;
use Modules\Power;
use Phalcon\Mvc;
use Modules\Lm;

class GoodsController extends ControllerBase
{

	private $goodsEnum = [
		'type' => ['0' => '否', '1' => '是'],
		'inType' => ['1' => '登记', '2' => '归还'],
		'outType' => ['1' => '登记', '2' => '领用'],
		'inStatus' => ['0' => '正常', '1' => '报废']
	];
	/**
	 * 物品类型-物品页
	 *
	 *
	 * create by qgz 20180711
	 */
	public function goodsListAction(){
		if (!Power::exist('Lm_GoodsList')) {
			return $this->sendViewError('对不起，您没有查看此页面的权限');
		}
		Main::showNavPosition();
		Assets::easyUI('js/goods/goodsList.js');
		$this->view->pick('goods/goodsList');
		$typeListButton = [];
		if(Power::exist('Lm_GoodsList_Add')){
			$typeListButton[] = array('plain' => 'true', 'id' => 'bt_type_add', 'text' => '新增', 'icon' => 'fa-plus');
		}
		if(Power::exist('Lm_GoodsList_Del')){
			$typeListButton[] = array('plain' => 'true', 'id' => 'bt_type_del', 'text' => '删除', 'icon' => 'fa-trash');
		}

		$goodsListButton = [];
		if(Power::exist('Lm_GoodsList_Add')){
			$goodsListButton[] = array('plain' => 'true', 'id' => 'bt_goods_add', 'text' => '新增', 'icon' => 'fa-plus');
		}
		if(Power::exist('Lm_GoodsList_Del')){
			$goodsListButton[] = array('plain' => 'true', 'id' => 'bt_goods_del', 'text' => '删除', 'icon' => 'fa-trash');
		}
		$this->view->setVars(array(
			'typeList' => Template::createList('typeList', 'goods_typeList', [
				'buttonToolbar' => Template::createButtonToolBar($typeListButton),
			]),
			'goodsList' => Template::createList('goodsList', 'goods_goodsList', [
				'buttonToolbar' => Template::createButtonToolBar($goodsListButton),
			]),
		));
	}

	/**
	 * 获取物品类型数据
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180711
	 */
	public function getGoodsTypeAction(){
		$params = ['columns' => '*', 'conditions' => 'bDelete = 0'];
		$data= Main::runModelPage('Admin\Models\lm\XHLmGoodsType', $params);
		Main::runUserNameById($data['rows'],['iCreateUserId'=>'iCreateUserId','iLastModifyUserId'=>'iLastModifyUserId'],true);
		return $this->sendJsonResponse($data);
	}

	/**
	 * 获取物品数据
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180711
	 */
	public function getGoodsDataAction(){
		$iTypeId = $this->request->getPost('iTypeId');
		$params = ['columns' => '*', 'conditions' => ' bDelete = 0 '];
		if ($iTypeId){
			$params['conditions'] .= ' and iGoodsType = :iGoodsType:';
			$params['bind'] = ['iGoodsType' => $iTypeId];
		}
		try {
//			if(!User::isAdmin()){
//				$nowUserId = Main::getLoginUserInfo('userId');
//				$depArr = User::getExtraPower('dep', 'goodsType', $nowUserId);
//				if($depArr){ //有额外权限
//					$userIds = Hrm::getUserByDepId($depArr, true);
//					if ($userIds) {
//						$params['conditions'] .= ' and (iCreateUserId in ({ids:array}) or iCreateUserId = :userId:) ';
//						if (isset($params['bind'])){
//							$params['bind'] = $params['bind'] + ['ids' => $userIds, 'userId' => $nowUserId];
//						}else{
//							$params['bind'] = ['ids' => $userIds, 'userId' => $nowUserId];
//						}
//					} else {
//						$params['conditions'] .= ' and iCreateUserId = :userId: ';
//						if (isset($params['bind'])){
//							$params['bind'] = $params['bind'] + ['userId' => $nowUserId];
//						}else{
//							$params['bind'] = ['userId' => $nowUserId];
//						}
//
//					}
//				}else{
//					$params['conditions'] .= ' and iCreateUserId = :userId: ';
//					if (isset($params['bind'])){
//						$params['bind'] = $params['bind'] + ['userId' => $nowUserId];
//					}else{
//						$params['bind'] = ['userId' => $nowUserId];
//					}
//				}
//			}
			$data= Main::runModelPage('Admin\Models\lm\XHLmGoods', $params, ['iType' => $this->goodsEnum['type']]);
			Main::runUserNameById($data['rows'],['iCreateUserId'=>'iCreateUserId','iLastModifyUserId'=>'iLastModifyUserId'],true);
			return $this->sendJsonResponse($data);
		} catch ( \Exception $e ) {
			return $this->sendErrorResponse( 500, $e->getMessage() );
		}
	}

	/**
	 * 增加或修改物品类型
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180711
	 */
	public function handleTypeDataAction(){
		if (!Power::exist('Lm_GoodsList_Edit')){
			return $this->sendViewError('你没有权限修改');
		}
		$postData = $this->request->getPost();
		if (!$postData['typeName']){
			return $this->sendErrorResponse(400, '请输入类型名');
		}
		if ($postData['type'] == 1){//创建
			$goodsType = new XHLmGoodsType();
		} else {//修改
			if (!$postData['id']){
				return $this->sendErrorResponse(400, '参数错误');
			}
			$goodsType = XHLmGoodsType::findFirst(['columns' => '*', 'conditions' => 'bDelete = 0 and iId = :iId:', 'bind' => ['iId' => $postData['id']]]);
			if (!$goodsType){
				return $this->sendErrorResponse(500, '暂无数据');
			}
		}
		$goodsType->sTypeName = $postData['typeName'];
		if (!$goodsType->save()){
			return $this->sendErrorResponse(500, '保存失败');
		}
		return $this->sendSuccessResponse('成功');
	}

	/**
	 * 增加和修改商品页面
	 *
	 * @return string
	 *
	 * create by qgz 20180712
	 */
	public function handleGoodsDataAction(){
		if (!Power::exist('Lm_GoodsList_Edit')){
			return $this->sendViewError('你没有权限修改');
		}
		$id = $this->request->getQuery('id');
		$typeId = $this->request->getQuery('typeId');
		$this->view->pick('goods/goodsForm');
		Assets::easyUI('js/goods/goodsForm.js');
		$types = XHLmGoodsType::find([
			'columns' => 'iId, sTypeName',
			'conditions' => ' bDelete = 0 ',
		])->toArray();
		if (empty($types)){
			return $this->sendViewError('暂无类型数据');
		}
		$allTypes = array_column($types,'sTypeName','iId');
		if ($id != null){
			$goods = XHLmGoods::findFirst([
				'conditions' => 'bDelete = 0 AND iId = :iId:',
				'bind' => ['iId' => $id],
			]);
			if (!$goods){
				return $this->sendViewError('暂无数据');
			}
			$goods = json_encode($goods->toArray());
		} else {
			$goods = 0;
		}
		$this->view->setVars([
			'goodsInfo' => $goods,
			'types' => $allTypes,
			'typeId' => $typeId
		]);
	}

	/**
	 * 保存创建或修改的物品数据
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180712
	 */
	public function saveGoodsDataAction(){
		$id = $this->request->getPost('id');
		$isCreate = $this->request->getPost('isCreate');
		$postData = $this->request->getPost();
		if ($id && $isCreate == 2){//修改
			$goodsObj = XHLmGoods::findFirst(['conditions' => 'bDelete = 0 AND iId = :iId:', 'bind' => ['iId' => $id]]);
			if (!$goodsObj){
				return $this->sendErrorResponse(400, '暂无数据');
			}
		} else {//创建
			$goodsObj = new XHLmGoods();
		}
		$goodsObj->iGoodsType = $postData['goodsTypeId'];
		$goodsObj->sGoodsName = $postData['goodsName'];
		$goodsObj->iUnit = $postData['unit'];
		$goodsObj->iType = $postData['type'];
		$goodsObj->sRemark = $postData['remark'];
		if (!$goodsObj->save()){
			return $this->sendErrorResponse(500, '保存出错');
		}
		return $this->sendSuccessResponse('成功');
	}

	/**
	 * 物品统计页面
	 *
	 * @return string
	 *
	 * create by qgz 20180712
	 */
	public function goodsStatAction(){
		if (!Power::exist('Lm_GoodsStat')) {
			return $this->sendViewError('对不起，您没有查看此页面的权限');
		}
		Main::showNavPosition();
		$this->view->pick('goods/goodsStat');
		Assets::easyUI('js/goods/goodsStat.js');
		$listSearchArr = $listButtonArr = [];
		$enum = ['' => '--消耗品--'] + $this->goodsEnum['type'];
		$listSearchArr[] = ['label' => '    ','type' => 'select', 'id' => 'list_search_type', 'data' => $enum];
		$listSearchArr[] = ['type' => 'text', 'id' => 'list_vague','label' => '   搜索：'];
		$this->view->setVars([
			'List' => Template::createList('list', 'goods_statList', [
				'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
				'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
			]),
		]);
	}

	/**
	 * 获取物品统计数据
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180712
	 */
	public function getGoodsStatAction(){
		$type = $this->request->getPost('type');
		try {
			$typesData = XHLmGoodsType::find([
				'columns' => 'iId, sTypeName',
				'conditions' => ' bDelete = 0 ',
			])->toArray();
			$types = array_column($typesData,'sTypeName','iId');
			$condition = ['conditions' => 'bDelete = 0'];
			if ($type === 0 || $type === '0' || $type === 1 || $type === '1'){
				$condition['conditions'] .= ' and iType = '.$type;
			}
//			if(!User::isAdmin()){//扩展权限
//				$nowUserId = Main::getLoginUserInfo('userId');
//				$depArr = User::getExtraPower('dep', 'goodsStat', $nowUserId);
//				if($depArr){ //有额外权限
//					$userIds = Hrm::getUserByDepId($depArr, true);
//					if ($userIds) {
//						$condition['conditions'] .= ' and (iCreateUserId in ({ids:array}) or iCreateUserId = :userId:) ';
//						$condition['bind'] = ['ids' => $userIds, 'userId' => $nowUserId];
//					} else {
//						$condition['conditions'] .= ' and iCreateUserId = :userId: ';
//						$condition['bind'] = ['userId' => $nowUserId];
//					}
//				}else{
//					$condition['conditions'] .= ' and iCreateUserId = :userId: ';
//					$condition['bind'] = ['userId' => $nowUserId];
//				}
//			}
			Main::runSearchVagueConditions($condition['conditions'], ['sGoodsName']);
			$data= Main::runModelPage('Admin\Models\lm\XHLmGoods', $condition, ['iGoodsType' => $types]);
			Main::runUserNameById($data['rows'],['iCreateUserId'=>'iCreateUserId','iLastModifyUserId'=>'iLastModifyUserId'],true);
			foreach ($data['rows'] as &$value){
				$value['iType'] = $value['iType'] == 0 ? '<i class="fa fa-laptop" title="非消耗品" ></i>' : '<i class="fa fa-glass" title="消耗品" ></i>';
			}
			return $this->sendJsonResponse($data);
		} catch ( \Exception $e ) {
			return $this->sendErrorResponse( 500, $e->getMessage() );
		}
	}

	/**
	 * 物品统计详情页
	 *
	 *
	 * create by qgz 20180712
	 */
	public function goodsDetailDataAction(){
		Assets::easyUI('js/goods/goodsDetail.js');
		Assets::importJs('js/myTool.js');
		$this->view->pick('goods/goodsDetail');
		$listSearchArr1 = $listSearchArr2 = [];
		$listSearchArr1[] = array('type' => 'text', 'id' => 'in_search', 'label' => ' 搜索： ');
		$listSearchArr1[] = array('type' => 'button', 'id' => 'bt_in_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
		$listSearchArr2[] = array('type' => 'text', 'id' => 'out_search', 'label' => ' 搜索： ');
		$listSearchArr2[] = array('type' => 'button', 'id' => 'bt_out_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
		$this->view->setVars(array(
			'inList' => Template::createList('inList', 'goods_inList', [
				'searchToolbar' => Template::createSearchToolBar($listSearchArr1, false),
				'checkbox' => false
			]),
			'outList' => Template::createList('outList', 'goods_outList', [
				'searchToolbar' => Template::createSearchToolBar($listSearchArr2, false),
				'checkbox' => false
			]),
		));
	}

	/**
	 * 获取物品登记详情
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180713
	 */
	public function getGoodsInDetailAction($showAll=false){
		$search = $this->request->getPost('search');
		$id = $this->request->getPost('id');
		$inType = $this->request->getPost('inType');
		$goodsType = $this->request->getPost('goodsType');
		$status = $this->request->getPost('status');
		$consume = $this->request->getPost('consume');
		try {
			$conditions = ' a.bDelete = 0 AND b.bDelete = 0 AND c.bDelete = 0 ';
			if ($search['vague']){
				if ($search['vague']){//搜索领用人和物品名称
					$userIdArr = Hrm::searchStaffUser($search['vague']);
					if (!empty($userIdArr)){
						$userIdArr = implode("','", $userIdArr);
						$conditions .= " AND ( b.sGoodsName LIKE '%{$search['vague']}%' OR a.iInUserId in ('" . $userIdArr . "'))";
					}else{
						$conditions .= " AND b.sGoodsName LIKE '%{$search['vague']}%'";
					}
				}
			}
			if ($id){
				$conditions .= " AND a.iGoodsId = {$id}";
			}
			if ($inType){
				$conditions .= " AND a.iInType = {$inType}";
			}
			if ($status != '' && $status !== null){
				$conditions .= " AND a.iInStatus = {$status}";
			}
			if ($goodsType){
				$conditions .= " AND b.iGoodsType = {$goodsType}";
			}
			if (in_array($consume, ['0', '1'])){
				$conditions .= " AND b.iType = {$consume}";
			}
//			if(!User::isAdmin() && !$showAll){//扩展权限
//				$nowUserId = Main::getLoginUserInfo('userId');
//				$depArr = User::getExtraPower('dep', 'goodsIn', $nowUserId);
//				if($depArr){ //有额外权限
//					$userIds = Hrm::getUserByDepId($depArr, true);
//					if ($userIds) {
//						$userIds = implode("','", $userIds);
//						$conditions .= " and (a.iCreateUserId in ('" . $userIds . "') or a.iCreateUserId = {$nowUserId}) ";
//					} else {
//						$conditions .= " and a.iCreateUserId = {$nowUserId} ";
//					}
//				}else{
//					$conditions .= " and a.iCreateUserId = {$nowUserId} ";
//				}
//			}
			$sql = [
				'columns' => 'c.sTypeName, b.sGoodsName, a.*',
				'query' => "SELECT :columns: FROM `XHLm_GoodsIn` a LEFT JOIN `XHLm_Goods` b ON a.iGoodsId = b.iId LEFT JOIN `XHLm_GoodsType` c ON c.iId = b.iGoodsType WHERE {$conditions} ORDER BY a.tCreateDate DESC "
			];
			$data = Main::runSqlPage($sql, ['iInType' => $this->goodsEnum['inType'], 'iInStatus' => $this->goodsEnum['inStatus']]);
			Main::runUserNameById($data['rows'],['iCreateUserId'=>'iCreateUserId','iLastModifyUserId'=>'iLastModifyUserId'],true);
            Hrm::runStaffNameByUserId($data['rows'],['iInUserId' => 'iInUserId'],true);
			$this->addColor($data['rows'], $this->goodsEnum['inStatus'], 'iInStatus');
			return $this->sendJsonResponse($data);
		} catch ( \Exception $e ) {
			return $this->sendErrorResponse( 500, $e->getMessage() );
		}
	}

	/**
	 * 添加颜色
	 *
	 * @return bool
	 *
	 * create by qgz 20180718
	 */
	public function addColor(&$data, $enum, $type){
		foreach ($data as &$value){
			switch ($value[$type]){
				case $enum['0']: $color = 'background-color: green;color:white'; break;
				case $enum['1']: $color = 'background-color: red;color:white'; break;
				default: $color = ''; break;
			}
			$value[$type] = '<div style="'.$color.'">'.$value[$type].'</div>';
		}
		return true;
	}

	/**
	 * 获取物品出库详情
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180719
	 */
	public function getGoodsOutDetailAction($showAll=false){
		$search = $this->request->getPost('search');
		$id = $this->request->getPost('id');
		$outType = $this->request->getPost('outType');
		$goodsType = $this->request->getPost('goodsType');
		$status = $this->request->getPost('status');
		$consume = $this->request->getPost('consume');
		try {
			$conditions = ' a.bDelete = 0 AND b.bDelete = 0 AND c.bDelete = 0 ';
			if ($search['vague']){//搜索领用人和物品名称
				$userIdArr = Hrm::searchStaffUser($search['vague']);
				if (!empty($userIdArr)){
					$userIdArr = implode("','", $userIdArr);
					$conditions .= " AND ( b.sGoodsName LIKE '%{$search['vague']}%' OR a.iOutUserId in ('" . $userIdArr . "'))";
				}else{
					$conditions .= " AND b.sGoodsName LIKE '%{$search['vague']}%'";
				}
			}
			if ($id){
				$conditions .= " AND a.iGoodsId = {$id}";
			}
			if ($outType){
				$conditions .= " AND a.iOutType = {$outType}";
			}
			if ($status != '' && $status !== null){
				$conditions .= " AND a.iOutStatus = {$status}";
			}
			if ($goodsType){
				$conditions .= " AND b.iGoodsType = {$goodsType}";
			}
			if (in_array($consume, ['0', '1'])){
				$conditions .= " AND b.iType = {$consume}";
			}
//			if(!User::isAdmin() && !$showAll){//扩展权限
//				$nowUserId = Main::getLoginUserInfo('userId');
//				$depArr = User::getExtraPower('dep', 'goodsOut', $nowUserId);
//				if($depArr){ //有额外权限
//					$userIds = Hrm::getUserByDepId($depArr, true);
//					if ($userIds) {
//						$userIds = implode("','", $userIds);
//						$conditions .= " and (a.iCreateUserId in ('" . $userIds . "') or a.iCreateUserId = {$nowUserId}) ";
//					} else {
//						$conditions .= " and a.iCreateUserId = {$nowUserId} ";
//					}
//				}else{
//					$conditions .= " and a.iCreateUserId = {$nowUserId} ";
//				}
//			}
			$sql = [
				'columns' => 'c.sTypeName, b.sGoodsName, a.*',
				'query' => "SELECT :columns: FROM `XHLm_GoodsOut` a LEFT JOIN `XHLm_Goods` b ON a.iGoodsId = b.iId LEFT JOIN `XHLm_GoodsType` c ON c.iId = b.iGoodsType WHERE {$conditions} ORDER BY a.tCreateDate DESC "
			];
			$data = Main::runSqlPage($sql, ['iOutType' => $this->goodsEnum['outType'], 'iOutStatus' => $this->goodsEnum['inStatus']]);
			Main::runUserNameById($data['rows'],['iCreateUserId'=>'iCreateUserId','iLastModifyUserId'=>'iLastModifyUserId'],true);
            Hrm::runStaffNameByUserId($data['rows'],['iOutUserId' => 'iOutUserId'],true);
			$this->addColor($data['rows'], $this->goodsEnum['inStatus'], 'iOutStatus');
			return $this->sendJsonResponse($data);
		} catch ( \Exception $e ) {
			return $this->sendErrorResponse( 500, $e->getMessage() );
		}
	}

	/**
	 * 物品登记记录详情页
	 *
	 * @return string
	 *
	 * create by qgz 20180713
	 */
	public function goodsInListAction(){
		if (!Power::exist('Lm_GoodsInList')) {
			return $this->sendViewError('对不起，您没有查看此页面的权限');
		}
		Main::showNavPosition();
		$this->view->pick('goods/goodsStat');//共用一个
		Assets::easyUI('js/goods/goodsInList.js');
		$types = XHLmGoodsType::find([
			'columns' => 'iId, sTypeName',
			'conditions' => ' bDelete = 0 ',
		])->toArray();
		$allTypes = array_column($types,'sTypeName','iId');
		$enum['inType'] = ['' => '--选择来源--'] + $this->goodsEnum['inType'];
		$enum['goodsType'] = ['' => '--选择类型--'] + $allTypes;
		$enum['status'] = ['' => '--选择状态--'] + $this->goodsEnum['inStatus'];
		$enum['consume'] = ['' => '--消耗品--'] + $this->goodsEnum['type'];
		$listSearchArr = $listButtonArr = [];
		$listSearchArr[] = ['label' => '    ','type' => 'select', 'id' => 'list_search_inType', 'data' => $enum['inType']];
		$listSearchArr[] = ['label' => '    ','type' => 'select', 'id' => 'list_search_goodsType', 'data' => $enum['goodsType']];
		$listSearchArr[] = ['label' => '    ','type' => 'select', 'id' => 'list_search_status', 'data' => $enum['status']];
		$listSearchArr[] = ['label' => '    ','type' => 'select', 'id' => 'list_search_consume', 'data' => $enum['consume']];
		$listSearchArr[] = ['type' => 'text', 'id' => 'list_vague','label' => '   搜索：'];
		if (Power::exist('Lm_GoodsInList_Add')){
			$listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
		}
		if (Power::exist('Lm_GoodsInList_Edit')) {
			$listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_editPrice', 'text' => '编辑价格', 'icon' => 'fa-edit');
		}
		if (Power::exist('Lm_GoodsInList_Del')){
			$listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
		}
		$this->view->setVars([
			'List' => Template::createList('list', 'goods_inDetailList', [
				'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
				'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
			]),
		]);
	}

	/**
	 * 新增物品登记页
	 *
	 * @return string
	 *
	 * create by qgz 20180713
	 */
	public function addGoodsInAction(){
		$this->view->pick('goods/goodsInForm');
		Assets::select2();
		Assets::easyUI('js/goods/goodsInForm.js');
		$types = XHLmGoodsType::find([
			'columns' => 'iId, sTypeName',
			'conditions' => ' bDelete = 0 ',
		])->toArray();
		if (empty($types)){
			return $this->sendViewError('暂无类型数据');
		}
		$allTypes = array_column($types,'sTypeName','iId');
		$this->view->setVars([
			'types' => $allTypes
		]);
	}

	/**
	 * 新增物品出库页
	 *
	 * @return string
	 *
	 * create by qgz 20180719
	 */
	public function addGoodsOutAction(){
		$this->view->pick('goods/goodsOutForm');
		Assets::select2();
		Assets::easyUI('js/goods/goodsOutForm.js');
		$types = XHLmGoodsType::find([
			'columns' => 'iId, sTypeName',
			'conditions' => ' bDelete = 0 ',
		])->toArray();
		if (empty($types)){
			return $this->sendViewError('暂无类型数据');
		}
		$allTypes = array_column($types,'sTypeName','iId');
		$this->view->setVars([
			'types' => $allTypes
		]);
	}

	/**
	 * 根据物品类型获取物品数据
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180713
	 */
	public function getGoodsByTypeAction(){
		$type = $this->request->getPost('goodsType');
		$params = ['columns' => 'iId, sGoodsName', 'conditions' => 'bDelete = 0 AND iGoodsType = :iGoodsType:', 'bind' => ['iGoodsType' => $type]];
		$data = XHLmGoods::find($params)->toArray();
		$data = array_column($data, 'sGoodsName', 'iId');
		return $this->sendJsonResponse($data);
	}

	/**
	 * 获取物品单位
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180713
	 */
	public function getUnitDataAction(){
		$goodsId = $this->request->getPost('goodsId');
		$params = ['columns' => 'iUnit', 'conditions' => 'bDelete = 0 AND iId = :iId:', 'bind' => ['iId' => $goodsId]];
		$data = XHLmGoods::findFirst($params);
		if ($data){
			return $this->sendJsonResponse('('.$data['iUnit'].')');
		} else {
			return $this->sendJsonResponse('');
		}
	}

	/**
	 * 获取员工数据
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180713
	 */
	public function getUserDataAction(){
		try {
			$return = [];
			$data = XhhrmStaff::getStaff();
			foreach ($data as $key=>$value){
				$newData[$key] = iconv('UTF-8', 'GBK', $value);//将数组先转换为GBK格式能对中文排序
			}
			asort($newData);
			foreach ($newData as $key=>$value) {
				$finaData[$key] = iconv('GBK', 'UTF-8', $value);
			}
			foreach ($finaData as $key => $value){
				$return[] = ['id' => $key, 'text' => $value];
			}
			return $this->sendJsonResponse($return);
		} catch ( \Exception $e ) {
			return $this->sendErrorResponse( 500, $e->getMessage());
		}
	}

	/**
	 * 保存物品登记数据
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180713
	 */
	public function saveInGoodsDataAction(){
		$postData = $this->request->getPost();
		if (!$postData['goodsId']){
			return $this->sendErrorResponse(400, '缺少商品id');
		}
        if ($postData['goodsName'] == '手机卡') {
            if (!$postData['phoneNum']) {
                return $this->sendErrorResponse(400, '请填写手机号');
            }
            $phoneArr = explode(',', $postData['phoneNum']);
            if (count($phoneArr) != $postData['num']) {
                return $this->sendErrorResponse(400, '请输入正确的手机号码，并且个数要与手机卡数一致。(多个请用英文,隔开)');
            }
            foreach ($phoneArr as $item) {
                if (!$item || !$this->checkTel($item)) {//检测手机号是否正确
                    return $this->sendErrorResponse(400, '请输入正确的手机号码，并且个数要与手机卡数一致。(多个请用英文,隔开)');
                }
            }
        }
		$params = [
			'id' => $postData['goodsId'],
			'time' => $postData['time'],
			'num' => $postData['num'],
			'type' => $postData['inType'],
			'userId' => $postData['buyUser'],
			'status' => $postData['status'],
			'price' => $postData['price'],
			'size' => $postData['size'],
			'remark' => $postData['remark'],
            'phoneNum' => $postData['phoneNum']
		];
		try {
			Lm::goodsInHandle($params);
			return $this->sendSuccessResponse('成功');
		} catch ( \Exception $e ) {
			return $this->sendErrorResponse( 500, $e->getMessage());
		}
	}

	/**
	 * 保存物品出库数据
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180719
	 */
	public function saveOutGoodsDataAction()
    {
		$postData = $this->request->getPost();
		if (!$postData['goodsId']) {
			return $this->sendErrorResponse(400, '缺少商品id');
		}
		if ($postData['goodsName'] == '手机卡') {
		    if (!$postData['phoneNum']) {
                return $this->sendErrorResponse(400, '请填写手机号');
            }
            $phoneArr = explode(',', $postData['phoneNum']);
            if (count($phoneArr) != $postData['num']) {
                return $this->sendErrorResponse(400, '请输入正确的手机号码，并且个数要与手机卡数一致。(多个请用英文,隔开)');
            }
            foreach ($phoneArr as $item) {
                if (!$item || !$this->checkTel($item)) {//检测手机号是否正确
                    return $this->sendErrorResponse(400, '请输入正确的手机号码，并且个数要与手机卡数一致。(多个请用英文,隔开)');
                }
            }
        }
		$params = [
			'id' => $postData['goodsId'],
			'time' => $postData['time'],
			'num' => $postData['num'],
			'type' => $postData['outType'],
			'userId' => $postData['outUser'],
			'status' => $postData['status'],
			'size' => $postData['size'],
			'remark' => $postData['remark'],
            'phoneNum' => $postData['phoneNum']
		];
		try {
			Lm::goodsOutHandle($params);
			return $this->sendSuccessResponse('成功');
		} catch ( \Exception $e ) {
			return $this->sendErrorResponse( 500, $e->getMessage());
		}
	}

    /**
     * 检测是否正确的手机号
     *
     * @param $phoneNum
     *
     * @return bool
     *
     * create by qgz 20181122
     */
    public function checkTel($phoneNum)
    {
        if (preg_match("/^1[345789]\d{9}$/", $phoneNum)) {
            return true;
        } else {
            return false;
        }
    }

	/**
	 * 修改物品价格
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180716
	 */
	public function modifyGoodsPriceAction(){
		$id = $this->request->getPost('id');
		$price = $this->request->getPost('price');
		if (!$id) {
			return $this->sendErrorResponse(400,'参数错误');
		}
		$goodsData = XHLmGoodsIn::findFirst(['conditions' => 'bDelete = 0 AND iId = :iId:', 'bind' => ['iId' => $id]]);
		if (!$goodsData){
			return $this->sendErrorResponse(500, '暂无物品数据');
		}
		$goodsData->iInPrice = $price;
		if (!$goodsData->save()){
			return $this->sendErrorResponse(500, '保存物品价格出错');
		}
		return $this->sendSuccessResponse('成功');
	}

	/**
	 * 修改出库备注
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180719
	 */
	public function modifyGoodsRemarkAction(){
		$id = $this->request->getPost('id');
		$remark = $this->request->getPost('remark');
		if (!$id) {
			return $this->sendErrorResponse(400,'参数错误');
		}
		$goodsData = XHLmGoodsOut::findFirst(['conditions' => 'bDelete = 0 AND iId = :iId:', 'bind' => ['iId' => $id]]);
		if (!$goodsData){
			return $this->sendErrorResponse(500, '暂无物品数据');
		}
		$goodsData->sRemark = $remark;
		if (!$goodsData->save()){
			return $this->sendErrorResponse(500, '保存物品价格出错');
		}
		return $this->sendSuccessResponse('成功');
	}

	/**
	 * 物品出库记录详情页
	 *
	 * @return string
	 *
	 * create by qgz 20180719
	 */
	public function goodsOutListAction(){
		if (!Power::exist('Lm_GoodsOutList')) {
			return $this->sendViewError('对不起，您没有查看此页面的权限');
		}
		Main::showNavPosition();
		$this->view->pick('goods/goodsStat');//共用一个
		Assets::easyUI('js/goods/goodsOutList.js');
		$types = XHLmGoodsType::find([
			'columns' => 'iId, sTypeName',
			'conditions' => ' bDelete = 0 ',
		])->toArray();
		$allTypes = array_column($types,'sTypeName','iId');
		$enum['outType'] = ['' => '--选择来源--'] + $this->goodsEnum['outType'];
		$enum['goodsType'] = ['' => '--选择类型--'] + $allTypes;
		$enum['status'] = ['' => '--选择状态--'] + $this->goodsEnum['inStatus'];
		$enum['consume'] = ['' => '--消耗品--'] + $this->goodsEnum['type'];
		$listSearchArr = $listButtonArr = [];
		$listSearchArr[] = ['label' => '    ','type' => 'select', 'id' => 'list_search_outType', 'data' => $enum['outType']];
		$listSearchArr[] = ['label' => '    ','type' => 'select', 'id' => 'list_search_goodsType', 'data' => $enum['goodsType']];
		$listSearchArr[] = ['label' => '    ','type' => 'select', 'id' => 'list_search_status', 'data' => $enum['status']];
		$listSearchArr[] = ['label' => '    ','type' => 'select', 'id' => 'list_search_consume', 'data' => $enum['consume']];
		$listSearchArr[] = ['type' => 'text', 'id' => 'list_vague','label' => '   搜索：'];
		if (Power::exist('Lm_GoodsOutList_Add')){
			$listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
		}
		if (Power::exist('Lm_GoodsOutList_Edit')) {
			$listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_editRemark', 'text' => '编辑备注', 'icon' => 'fa-edit');
		}
		if (Power::exist('Lm_GoodsOutList_Del')){
			$listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
		}
		$this->view->setVars([
			'List' => Template::createList('list', 'goods_outDetailList', [
				'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
				'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
			]),
		]);
	}

	/**
	 * 删除物品类型
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180716
	 */
	public function delTypeDataAction(){
		$id = $this->request->getPost('id');
		if (!$id) {
			return $this->sendErrorResponse(400,'参数错误');
		}
		$this->db->begin();
		$data = XHLmGoodsType::findFirst(['conditions' => 'bDelete = 0 AND iId = :iId:', 'bind' => ['iId' => $id]]);
		if (!$data){
			$this->db->rollback();
			return $this->sendErrorResponse(500, '暂无物品类型数据');
		}
		$data->bDelete = 1;
		if (!$data->save()){
			$this->db->rollback();
			return $this->sendErrorResponse(500, '删除物品类型数据出错');
		}
		$sql = "update XHLm_Goods set bDelete = 1 where bDelete = 0 AND iGoodsType = {$id}";
		$updateData = $this->db->execute($sql);
		if (!$updateData){
			$this->db->rollback();
			return $this->sendErrorResponse(500, '删除物品数据失败');
		}
		$this->db->commit();
		return $this->sendSuccessResponse('成功');
	}

	/**
	 * 删除物品
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180716
	 *
	 */
	public function delGoodsDataAction(){
		$ids = $this->request->getPost('ids');
		if (empty($ids)) {
			return $this->sendErrorResponse(400,'参数错误');
		}
		$this->db->begin();
		$data = XHLmGoods::find(['conditions' => 'bDelete = 0 AND iId in ({idArr:array})', 'bind' => ['idArr' => $ids]]);
		if (!$data){
			$this->db->rollback();
			return $this->sendErrorResponse(500, '暂无物品数据');
		}
		foreach ($data as $value){
			$value->bDelete = 1;
			if (!$value->save()){
				$this->db->rollback();
				return $this->sendErrorResponse(500, '删除物品数据错误');
			}
		}
		$this->db->commit();
		return $this->sendSuccessResponse('成功');
	}

	/**
	 * 删除登记表数据
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180716
	 */
	public function delGoodsInDataAction(){
		$ids = $this->request->getPost('ids');
		if (empty($ids)) {
			return $this->sendErrorResponse(400,'参数错误');
		}
		$this->db->begin();
		$data = XHLmGoodsIn::find(['conditions' => 'bDelete = 0 AND iId in ({idArr:array})', 'bind' => ['idArr' => $ids]]);
		if (!$data){
			$this->db->rollback();
			return $this->sendErrorResponse(500, '暂无物品数据');
		}
		foreach ($data as $value){
			$value->bDelete = 1;
			if (!$value->save()){
				$this->db->rollback();
				return $this->sendErrorResponse(500, '删除登记数据错误', 'ID:'.$value->iId);
			}
			$findData = XHLmGoods::findFirst(['conditions' => 'bDelete = 0 AND iId = :id:', 'bind' => ['id' => $value->iGoodsId]]);
			$num = Lm::getNumData('out', $value->iInNum, $value->iInType, $value->iInStatus, $findData->iType);
			$findData->iNum -= $num['store'];
			$findData->iAllNum -= $num['all'];
			if (!$findData->save()){
				$this->db->rollback();
				return $this->sendErrorResponse(500, '修改物品数量错误', 'ID:'.$findData->iId);
			}
		}
		$this->db->commit();
		return $this->sendSuccessResponse('成功');
	}

	/**
	 * 删除领用表数据
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180716
	 */
	public function delGoodsOutDataAction(){
		$ids = $this->request->getPost('ids');
		if (empty($ids)) {
			return $this->sendErrorResponse(400,'参数错误');
		}
		$this->db->begin();
		$data = XHLmGoodsOut::find(['conditions' => 'bDelete = 0 AND iId in ({idArr:array})', 'bind' => ['idArr' => $ids]]);
		if (!$data){
			$this->db->rollback();
			return $this->sendErrorResponse(500, '暂无物品数据');
		}
		foreach ($data as $value){
			$value->bDelete = 1;
			if (!$value->save()){
				$this->db->rollback();
				return $this->sendErrorResponse(500, '删除领用数据错误', 'ID:'.$value->iId);
			}
			$findData = XHLmGoods::findFirst(['conditions' => 'bDelete = 0 AND iId = :id:', 'bind' => ['id' => $value->iGoodsId]]);
			$num = Lm::getNumData('in', $value->iOutNum, $value->iOutType, $value->iOutStatus, $findData->iType);
			$findData->iNum += $num['store'];
			$findData->iAllNum += $num['all'];
			if (!$findData->save()){
				$this->db->rollback();
				return $this->sendErrorResponse(500, '修改物品数量错误', 'ID:'.$findData->iId);
			}
		}
		$this->db->commit();
		return $this->sendSuccessResponse('成功');
	}

	/**
	 * 更新库存数量
	 *
	 * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
	 *
	 * create by qgz 20180725
	 */
	public function updateGoodsNumAction(){
		try {
			$this->db->begin();
			$id = $this->request->get('id','int');
			if ($id) {
				$in = XHLmGoodsIn::find([
					'conditions' => 'bDelete = 0 and iGoodsId = :iGoodsId:',
					'bind'    => ['iGoodsId' => $id]
				])->toArray();
				$out = XHLmGoodsOut::find([
					'conditions' => 'bDelete = 0 and iGoodsId = :iGoodsId:',
					'bind'    => ['iGoodsId' => $id]
				])->toArray();
				$total = 0;
				if ($in) {
					foreach ($in as $row) {
						$total += $row['iInNum'];
					}
				}
				$all = $total;
				if ($out) {
					foreach ($out as $row) {
						$total -= $row['iOutNum'];
					}
				}
				$obj = XHLmGoods::findFirst([ 'conditions' => 'iId = :iId:', 'bind' => ['iId' => $id]]);
				if(!$obj){
					return $this->sendErrorResponse(400, '未找到物品');
				}
				$obj->iNum = $total;
				$obj->iAllNum = $all;
				if (!$obj->save()) {
					$this->db->rollback();
					return $this->sendErrorResponse(500,'成功');
				}
			} else {
				$in = XHLmGoodsIn::find([
					'conditions' => 'bDelete = 0 '
				])->toArray();
				$out = XHLmGoodsOut::find([
					'conditions' => 'bDelete = 0 '
				])->toArray();
				$arr = [];
				foreach ($in as $row) {
					$arr[$row['iGoodsId']] = Tool::getValue($arr, $row['iGoodsId'], 0) + $row['iInNum'];
				}
				$all = $arr;
				foreach ($out as $row) {
					$arr[$row['iGoodsId']] = Tool::getValue($arr, $row['iGoodsId'], 0) - $row['iOutNum'];
				}
				$goodsArr = XHLmGoods::find([
					'conditions' => 'bDelete = 0'
				]);
				foreach ($goodsArr as $goods) {
					$goods->iNum = Tool::getValue($arr, $goods->iId, 0);
					$goods->iAllNum = Tool::getValue($all, $goods->iId, 0);
					if (!$goods->save()) {
						$this->db->rollback();
						return $this->sendErrorResponse(500, '成功');
					}
				}
			}
			$this->db->commit();
			return $this->sendSuccessResponse('更新成功');
		} catch (\Exception $e) {
			$this->db->rollback();
			return $this->sendErrorResponse(500, $e->getMessage());
		}

	}

}